package com.sensePlusVR.realGame;

import android.util.Log;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class RealGameConfig {
	private static final String TAG="RealGameConfig";
	public static final int CODED_HEVC = 0;
	public static final int CODED_h264 = 1;
	public static final int TYPE_START = 0;
	public static final int TYPE_END = 1;
	public static final int TYPE_NORMAL = 2;
	private File configFile;
	private SimapleAction mStart;
	private SimapleAction mEnd;
	private List<SimapleAction> mActions;
	private SimapleAudio mAudioFile;
	//private int mActionIndex;
	private int mSourceType;
	private int mConfigVersion;
	private int mActionsNr = 0;
	
	public int getActionsNumber(){
		return mActionsNr;
	}
	
	public RealGameConfig(String file){
		configFile = new File(file);
		mActions = new ArrayList<SimapleAction>();
		//mActionIndex = 0;
		if(file.endsWith(".json"))
			ParseJsonConfig();
		else
			ParseConfig();
	}
	
	public boolean supportVideo(){
		SimapleAction s = mActions.get(0);
		if (s.toString() != null && s.getmDesVideo() != null)
			return true;
		return false;
	}
	
	public int getActionVideoWidth(){
		return mActions.get(0).getmCodecWidth();
	}
	
	public int getActionVideoHeight(){
		return mActions.get(0).getmCodecHeight();
	}
	
	public SimapleAudio getBackAudio(){
		return mAudioFile;
	}
	
	public byte[] getStartAction(){
		return mStart.toByte();
	}
	
	public int getStartVideoWidth(){
		return mStart.getmCodecWidth();
	}
	public int getStartVideoHeight(){
		return mStart.getmCodecHeight();
	}
	public String getStartActionVideo(){
		return mStart.getmVideoFile();
	}
	public String getStartActionVideo2(){
		return mStart.getmVideoFile2();
	}
	public byte[] getEndAction(){
		return mEnd.toByte();
	}
	
	public int getEndVideoWidth(){
		return mEnd.getmCodecWidth();
	}
	public int getEndVideoHeight(){
		return mEnd.getmCodecHeight();
	}
	
	public String getEndActionVideo(){
		return mEnd.getmVideoFile();
	}	
	public String getEndActionVideo2(){
		return mEnd.getmVideoFile2();
	}
	
	public List<SimapleAction> getActions(int actionMain){
		List<SimapleAction> list = new ArrayList<SimapleAction>();
		for (SimapleAction sa: mActions){
			if (sa.getMainAction() == actionMain){
				list.add(sa);
			}
		}
		return list;
	}
	public int getSourceType()
	{
		return mSourceType;
	}
	
	public int getConfigVersion()
	{
		return mConfigVersion;
	}

	/**
	 * 
	 */
	private void ParseJsonConfig()
	{
		JsonParser parser = new JsonParser();
		String dir = configFile.getParent();
		if (mStart == null)
			mStart = new SimapleAction();
		if (mEnd == null)
			mEnd   = new SimapleAction();
		if (mAudioFile == null)
			mAudioFile = new SimapleAudio();
		SimapleAction action = null;
		Log.e(TAG, "ParseJsonConfig");
		try
		{
			JsonObject json = (JsonObject)parser.parse(new FileReader(configFile));
			int version       = json.get("version").getAsInt();
			mConfigVersion = version;
			Log.e(TAG, "ParseJsonConfig!"+version);
			
			mSourceType       = json.get("sourcetype").getAsInt();
			String desc       = json.get("desc").getAsString();
			
			JsonArray  audiobackarray = json.get("audioback").getAsJsonArray();
			for (int i = 0; i < audiobackarray.size(); i++)
			{
				mAudioFile.addAudioFile(dir+File.separatorChar+audiobackarray.get(i).getAsString());
			}
			
			String startvideo      = dir+File.separatorChar+json.get("startvideo").getAsString();
			mStart.setType(TYPE_START);
			mStart.setmVideoFile(startvideo);
			
			String endingvideo     = dir+File.separatorChar+json.get("endingvideo").getAsString();
			mEnd.setType(TYPE_END);
			mEnd.setmVideoFile(endingvideo);
			
			JsonArray  actionarray = json.get("action").getAsJsonArray();
			Log.e(TAG, "action's count="+actionarray.size());
			mActionsNr = actionarray.size();
			for (int i = 0; i < actionarray.size(); i++)
			{
				Log.e(TAG, "ParseJsonConfig action");
				if (!actionarray.get(i).isJsonObject()){
					Log.e(TAG, "action index="+i+" is not json object");
				}
				JsonObject actionindex = actionarray.get(i).getAsJsonObject();
				int main    = actionindex.get("main").getAsInt();
				int fov     = actionindex.get("fov").getAsInt();
				String name = actionindex.get("name").getAsString();
				JsonArray videoarray     = actionindex.get("video").getAsJsonArray();
				String desVideo = videoarray.get(0).getAsString();
				if (desVideo != null && !desVideo.isEmpty() && !desVideo.equals(""))
					desVideo = dir + File.separatorChar + videoarray.get(0).getAsString();
				else
					desVideo = null;
				JsonArray subactionarray = actionindex.get("subaction").getAsJsonArray();
				Log.e(TAG, "subaction's count="+subactionarray.size());
				if (subactionarray.size() <= 0){
					action = new SimapleAction();
					action.setType(TYPE_NORMAL);
					action.setVersion(version);
					action.setMainAction(main);
					action.setFov(fov);
					action.setName(name);
					action.setmDesVideo(desVideo);
					mActions.add(action);
					continue;
				}
				for (int j = 0; j < subactionarray.size(); j++)
				{
					Log.e(TAG, "ParseJsonConfig subaction");
					if (!subactionarray.get(j).isJsonObject()){
						Log.e(TAG, "subaction index="+j+" is not a json object");
						continue;	
					}
					JsonObject subactionindex = subactionarray.get(j).getAsJsonObject();
					action = new SimapleAction();
					action.setType(TYPE_NORMAL);
					action.setVersion(version);
					action.setMainAction(main);
					action.setFov(fov);
					action.setName(name);
					action.setmDesVideo(desVideo);
					mActions.add(action);
					
					int minor = subactionindex.get("minor").getAsInt();
					action.setMinorAction(minor);
					JsonArray videofile = subactionindex.get("videofile").getAsJsonArray();
					String streamfile = dir+File.separatorChar + videofile.get(0).getAsString();
					action.setmVideoFile(streamfile);
					String streamfile2    = dir+File.separatorChar + videofile.get(1).getAsString();
					action.setmVideoFile2(streamfile2);
					//action.setmVideoStreamlenFile(lenfile);
					if (version == 3){
						String highvideo    = dir+File.separatorChar + videofile.get(2).getAsString();
						action.setmVideoFileHigh(highvideo);
					}
					
					JsonArray audioidle = subactionindex.get("audioidle").getAsJsonArray();
					String audioidlestr = null;
					for (int k = 0; k < audioidle.size(); k++)
					{
						if (audioidlestr == null)
							audioidlestr = audioidle.get(k).getAsString();
						audioidlestr += ","+audioidle.get(k).getAsString();
					}
					Log.e(TAG, "audioidle:"+audioidlestr);
					action.setmAudioIdle(dir+File.separatorChar, audioidlestr);
					
					JsonArray audiolow  = subactionindex.get("audiolow").getAsJsonArray();
					String audiolowstr = null;
					for (int k = 0; k < audiolow.size(); k++)
					{
						if (audiolowstr == null)
							audiolowstr = audiolow.get(k).getAsString();
						audiolowstr += ","+audiolow.get(k).getAsString();
					}
					Log.e(TAG, "audiolow:"+audiolowstr);
					action.setmAudioLow(dir+File.separatorChar, audiolowstr);
					
					JsonArray audiomid  = subactionindex.get("audiomid").getAsJsonArray();
					String audiomidstr = null;
					for (int k = 0; k < audiomid.size(); k++)
					{
						if (audiomidstr == null)
							audiomidstr = audiomid.get(k).getAsString();
						audiomidstr += ","+audiomid.get(k).getAsString();
					}
					Log.e(TAG, "audiomid:"+audiomidstr);
					action.setmAudioMid(dir+File.separatorChar, audiomidstr);
					
					JsonArray audiohigh = subactionindex.get("audiohigh").getAsJsonArray();
					String audiohighstr = null;
					for (int k = 0; k < audiohigh.size(); k++)
					{
						if (audiohighstr == null)
							audiohighstr = audiohigh.get(k).getAsString();
						audiohighstr += ","+audiohigh.get(k).getAsString();
					}
					Log.e(TAG, "audiohigh:"+audiohighstr);
					action.setmAudioHeigh(dir+File.separatorChar, audiohighstr);
				}
				
			}
		}
		catch (Exception e)
		{
			Log.e(TAG, "ParseJsonConfig error!"+e.getMessage());
		}
	}
	
	
	private void ParseConfig(){
		BufferedReader reader = null;
		String tempString = null;
		SimapleAction action = null;
		try {
			String dir = configFile.getParent();
			reader = new BufferedReader(new FileReader(configFile));
            while ((tempString = reader.readLine()) != null) {
            	String t[] = tempString.split(":");
                //System.out.println("line " + line + ": " + tempString);
            	if (t[0].equals("##TYPE")){
            		if (t[1].equals("start")){
            			action = new SimapleAction();
            			mStart = action;
            			action.setType(TYPE_START);
            		}else if (t[1].equals("end")){
            			action = new SimapleAction();
            			mEnd = action;
            			action.setType(TYPE_END);
            		}else if (t[1].equals("action")){
            			action = new SimapleAction();
            			mActions.add(action);
            			action.setType(TYPE_NORMAL);
            		}else if (t[1].equals("audioback")){
            			mAudioFile = new SimapleAudio();
            		}
            	}else if (t[0].equals("#ACTION")){
            		String acs[] = t[1].split("-");
            		action.setMainAction(Integer.valueOf(acs[0]));
            		action.setMinorAction(Integer.valueOf(acs[1]));
            	}else if (t[0].equals("#NAME")){
            		action.setName(t[1]);
            	}else if (t[0].equals("#CODEC")){
            		action.setmCodecType(Integer.valueOf(t[1]));
            	}else if (t[0].equals("#WIDTH")){
            		action.setmCodecWidth(Integer.valueOf(t[1]));
            	}else if (t[0].equals("#HEIGHT")){
            		action.setmCodecHeight(Integer.valueOf(t[1]));
            	}else if (t[0].equals("#RATE")){
            		action.setmCodecFps(Integer.valueOf(t[1]));
            	}else if (t[0].equals("#SRC_FILE")){
            		action.setmVideoFile(dir+File.separatorChar+t[1]);
            	}else if (t[0].equals("#SRC_FILE2")){
            		action.setmVideoFile2(dir+File.separatorChar+t[1]);
            	}else if (t[0].equals("#LEN_FILE")){
            		action.setmVideoStreamlenFile(dir+File.separatorChar+t[1]);
            	}else if (t[0].equals("#REVERSED")){
            		action.setmReversed(Integer.valueOf(t[1]));
            	}else if (t[0].equals("#AUDIOLOW")){
            		action.setmAudioLow(dir+File.separatorChar, t[1]);
            	}else if (t[0].equals("#AUDIOMID")){
            		action.setmAudioMid(dir+File.separatorChar, t[1]);
            	}else if (t[0].equals("#AUDIOHEIGH")){
            		action.setmAudioHeigh(dir+File.separatorChar, t[1]);
            	}else if (t[0].equals("#AUDIOIDLE")){
            		action.setmAudioIdle(dir+File.separatorChar, t[1]);
            	}else if (t[0].equals("#AUDIO_FILE")){
            		String sp[] = t[1].split(",");
            		for (String s:sp){
            			mAudioFile.addAudioFile(dir+File.separatorChar+s);
            		}
            	}
            }
            reader.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.e(TAG, "get audio"+mAudioFile.getRandomAudio());
	}
}
